package com.neuedu.helloworld;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.neuedu.helloworld.ticket.StationActivity;
import com.neuedu.helloworld.ticket.Ticket2Activity;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class TicketFragment extends Fragment  implements View.OnClickListener {



    private ListView lvTicketHistory ;
    private ArrayAdapter adapter ;
    private List<String> data = new ArrayList<>();
    private TextView tvStartTime;
    private TextView tvFrom;
    private TextView tvTo;
    private Button btnQuery;
    private ImageView animation;

    private int currentVersion = 10;
    private String fileName = "station_log";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ticket, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lvTicketHistory = getActivity().findViewById(R.id.lvTicketHistory);
        tvFrom = getActivity().findViewById(R.id.tvFrom);
        animation = getActivity().findViewById(R.id.animation);
        tvTo = getActivity().findViewById(R.id.tvTo);
        tvStartTime = getActivity().findViewById(R.id.tvStartTime);
        btnQuery = getActivity().findViewById(R.id.btnQuery);

        //出发城市，到达城市
        tvFrom.setOnClickListener(this);
        tvTo.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        btnQuery.setOnClickListener(this);



       initStationLog();

        adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1,data);

        lvTicketHistory.setAdapter(adapter);

        animation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startAnimation();


            }
        });

    }

    private void initStationLog() {

        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getActivity(),fileName,null,currentVersion );
        SQLiteDatabase readDB = helper.getReadableDatabase();


        Cursor cursor = readDB.rawQuery("select id,station_from , station_to from  station_log ", null);

        while (cursor.moveToNext()){
            String station_from = cursor.getString(cursor.getColumnIndex("station_from"));
            String station_to = cursor.getString(cursor.getColumnIndex("station_to"));
            data.add(station_from+ "--- "+station_to);
        }


    }

    private void startAnimation() {

        TranslateAnimation annimationLeft = new TranslateAnimation(0, 220, 0,   0);
        annimationLeft.setInterpolator(new LinearInterpolator());
        //执行
        annimationLeft.setDuration(800);

        annimationLeft.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                tvFrom.getText();
//                tvTo.getText();

                CharSequence fromTemp = tvFrom.getText();
                tvFrom.setText(tvTo.getText());
                tvTo.setText(fromTemp);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        tvFrom.startAnimation(annimationLeft);




        TranslateAnimation annimationRight = new TranslateAnimation(0, -220, 0,   0);
        annimationRight.setInterpolator(new LinearInterpolator());
        //执行
        annimationRight.setDuration(800);

        tvTo.startAnimation(annimationRight);

    }

    @Override
    public void onClick(View v) {

        //三个textview 都会调用此方法
        if( v.getId() == R.id.tvFrom || v.getId() == R.id.tvTo){
            Intent intent  = new Intent(getActivity(), StationActivity.class);
            startActivityForResult(intent,v.getId());
        }else  if(v.getId() == R.id.tvStartTime){


            chooiceTime();

        }else if(v.getId() == R.id.btnQuery){

            //将出发城市、到达城市 存储到 SQLite数据库中
//            int currentVersion = 1;

            MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getActivity(),fileName,null,currentVersion );



            SQLiteDatabase writeDB = helper.getWritableDatabase();


            // insert into station_log (id,from,to) values(?,?,?)
            /**
             *    "\t\"id\"\tINTEGER PRIMARY KEY AUTOINCREMENT,\n" +
             *                     "\t\"station_from\"\tTEXT,\n" +
             *                     "\t\"station_to\"\tTEXT\n" +
             *                     ")");
             */

            ContentValues values = new ContentValues();
            values.put("station_from",tvFrom.getText().toString());
            values.put("station_to",tvTo.getText().toString());

            writeDB.insert("station_log", null,values);

            writeDB.close();
            helper.close();

            Intent intent = new Intent(getActivity(), Ticket2Activity.class);
            startActivity(intent);




        }




    }

    private void chooiceTime() {
        //2022/05/30 星期一
        String strTvFromStartTime = tvStartTime.getText().toString();
        //2022/05/30
        strTvFromStartTime = strTvFromStartTime.split(" ")[0];
        String[] time = strTvFromStartTime.split("/");
        //time[0] 2022
        //time[1]  5
        //time[2] 30

        //选择出发时间
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //如果选择 2022年7月20日   year = 2022  month ；6  dayOfMonth 20

                Toast.makeText(getActivity(), "选择的dayOfMonth："+dayOfMonth, Toast.LENGTH_SHORT).show();
                Date selectDate = new Date(year-1900,month,dayOfMonth);
//                    Calendar
                //DateUtils.FORMAT_SHOW_WEEKDAY从日期毫秒对象中获取星期（星期一、星期二、   周一、周二   Monday  Mon 、Tur）
                String weekday = DateUtils.formatDateTime(getActivity(), selectDate.getTime(),
                        DateUtils.FORMAT_SHOW_WEEKDAY|DateUtils.FORMAT_ABBREV_WEEKDAY);

//                    Toast.makeText(getActivity(), "weekday: "+weekday, Toast.LENGTH_SHORT).show();

                Log.d("weekday",weekday);
                //选择日期后，调用此事件
                tvStartTime.setText(""+year+"/"+(month+1)+"/"+dayOfMonth+" "+weekday);
            }
        },      Integer.parseInt(time[0]),
                Integer.parseInt(time[1]) - 1,// 月份从0 开始，
                Integer.parseInt(time[2])
        );

        dialog.show();


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null) {
            String stationName = data.getStringExtra("stationName");
            if(stationName == null || stationName.length()==0){
                return;
            }

            if (requestCode == R.id.tvFrom) {
                tvFrom.setText(stationName);
            } else if (requestCode == R.id.tvTo) {
                tvTo.setText(stationName);
            }
        }
    }


    /**
     *  2023-5-24   new MySQLiteOpenHelper（  version = 1）
     *  2023-6-24   new MySQLiteOpenHelper（  version = 2）   age
     *
     *  SQLiteDatabase db   <----- MySQLiteOpenHelper
     *
     *  db.rawQuery update
     */

    class MySQLiteOpenHelper extends SQLiteOpenHelper {

        public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
            super(context, name, factory, version, errorHandler);
        }

        public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, int version, @NonNull SQLiteDatabase.OpenParams openParams) {
            super(context, name, version, openParams);
        }





        //当第一次用的时候， 创建数据库
        @Override
        public void onCreate(SQLiteDatabase db) {
            //执行一些初始化的 代码   create table test(id,name)
            //需要创建表

            db.execSQL("CREATE TABLE \"station_log\" (\n" +
                    "\t\"id\"\tINTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                    "\t\"station_from\"\tTEXT,\n" +
                    "\t\"station_to\"\tTEXT\n" +
                    ")");
        }


        /**
         * 程序升级的时候用
         * @param db
         * @param oldVersion
         * @param newVersion
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //版本升级的代码

            String msg = String.format("版本升级了，newVersion:%s ， oldVersion ：%s ",newVersion,oldVersion);
            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();

        }

//        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//            throw new SQLiteException("Can't downgrade database from version " +
//                    oldVersion + " to " + newVersion);
//        }

    }




}